/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/5/22.
//

#include "common/rc.h"
#include "common/log/log.h"
#include "common/lang/string.h"
#include "sql/stmt/filter_stmt.h"
#include "storage/db/db.h"
#include "storage/table/table.h"
#include "sql/stmt/select_stmt.h"
FilterStmt::~FilterStmt()
{
  for (FilterUnit *unit : filter_units_) {
    delete unit;
  }
  filter_units_.clear();
}
FilterStmt::FilterStmt(const FilterStmt &other)
{
  this->filter_units_.clear();
  for (FilterUnit *unit : other.filter_units_) {
    if (unit != nullptr) {
      FilterUnit *tmp = new FilterUnit(*unit);
      this->filter_units_.push_back(tmp);
    }
  }
}
FilterStmt &FilterStmt::operator=(const FilterStmt &other)
{
  this->filter_units_.clear();
  for (FilterUnit *unit : other.filter_units_) {
    FilterUnit *tmp = new FilterUnit(*unit);
    this->filter_units_.push_back(tmp);
  }
  return *this;
}
FilterObj::FilterObj(const FilterObj &other)
{
  this->condition_type = other.condition_type;
  this->field          = other.field;
  this->value          = other.value;
  this->value_list     = other.value_list;
  if (other.stmt != nullptr) {
    this->stmt = new SelectStmt(*(SelectStmt *)other.stmt);
  }
}
FilterObj &FilterObj::operator=(const FilterObj &other)
{
  this->condition_type = other.condition_type;
  this->field          = other.field;
  this->value          = other.value;
  this->value_list     = other.value_list;
  if (other.stmt != nullptr) {
    this->stmt = new SelectStmt(*(SelectStmt *)other.stmt);
  }
  return *this;
}
int FilterObj::cell_num(){
  switch(condition_type){
      case ConditionType::C_ATTR:{
        return 1;
      }break;
      case ConditionType::C_VALUE:{
        return 1;
      }break;
      case ConditionType::C_SQL:{
        return ((SelectStmt*)stmt)->cell_num();
      }break;
      case ConditionType::C_VALUE_LIST:{
        return 1;
      }break;
      case ConditionType::C_NULL:{
        return 1;
      }break;
    }
}
int FilterObj::row_num(){
  switch(condition_type){
      case ConditionType::C_ATTR:{
        return 1;
      }break;
      case ConditionType::C_VALUE:{
        return 1;
      }break;
      case ConditionType::C_SQL:{
        return !(((SelectStmt*)stmt)->func_types().empty());
      }break;
      case ConditionType::C_NULL:{
        return 0;
      }
    }
}
bool FilterUnit::check(){
  if(left_.condition_type==ConditionType::C_NULL&&right_.condition_type==ConditionType::C_SQL)return true;
  if(right_.condition_type==ConditionType::C_NULL&&left_.condition_type==ConditionType::C_SQL)return true;
  bool cell_check=left_.cell_num()==right_.cell_num();
  // bool row_check=left_.row_num()==right_.row_num();
  // row_check=row_check||(comp_>=CompOp::_IN&&comp_<CompOp::NO_OP);
  return cell_check;
}
RC FilterStmt::create(Db *db, Table *default_table, std::vector<Field> default_fields,std::unordered_map<std::string, Table *> *tables,
    const ConditionSqlNode *conditions, int condition_num, FilterStmt *&stmt,std::vector<std::string> p_tables)
{
  RC rc = RC::SUCCESS;
  stmt  = nullptr;

  FilterStmt *tmp_stmt = new FilterStmt();
  for (int i = 0; i < condition_num; i++) {
    FilterUnit *filter_unit = nullptr;
    rc                      = create_filter_unit(db, default_table, default_fields,tables, conditions[i], filter_unit,p_tables);
    if (rc != RC::SUCCESS) {
      delete tmp_stmt;
      LOG_WARN("failed to create filter unit. condition index=%d", i);
      return rc;
    }
    tmp_stmt->filter_units_.push_back(filter_unit);
  }
  stmt = tmp_stmt;
  return rc;
}

RC get_table_and_field(Db *db, Table *default_table, std::unordered_map<std::string, Table *> *tables,
    const RelAttrSqlNode &attr, Table *&table, const FieldMeta *&field,std::vector<std::string> p_tables=std::vector<std::string>())
{ 
  table=nullptr;
  if (common::is_blank(attr.relation_name.c_str())) {
    table = default_table;
  } 
  if (table==nullptr&&nullptr != tables) {
    auto iter = tables->find(attr.relation_name);
    if (iter != tables->end()) {
      table = iter->second;
    }
  }
  if(table==nullptr) {
    auto iter=std::find(p_tables.begin(),p_tables.end(),attr.relation_name.c_str());
    if(iter!=p_tables.end()){
    table = db->find_table(attr.relation_name.c_str());
    }
  }
  if (nullptr == table) {
    LOG_WARN("No such table or isn't p_table: attr.relation_name: %s", attr.relation_name.c_str());
    return RC::SCHEMA_TABLE_NOT_EXIST;
  }

  field = table->table_meta().field(attr.attribute_name.c_str());
  if (nullptr == field) {
    LOG_WARN("no such field in table: table %s, field %s", table->name(), attr.attribute_name.c_str());
    table = nullptr;
    return RC::SCHEMA_FIELD_NOT_EXIST;
  }

  return RC::SUCCESS;
}

RC FilterStmt::create_filter_unit(Db *db, Table *default_table, std::vector<Field> default_fields,std::unordered_map<std::string, Table *> *tables,
    const ConditionSqlNode &condition, FilterUnit *&filter_unit,std::vector<std::string> p_tables)
{
  if (condition.left_type == C_VALUE && condition.left_value.attr_type() == DATES &&
      condition.left_value.get_date() == -1) {
    return RC::GENERIC_ERROR;
  }
  if (condition.right_type == C_VALUE && condition.right_value.attr_type() == DATES &&
      condition.right_value.get_date() == -1) {
    return RC::GENERIC_ERROR;
  }
  RC     rc   = RC::SUCCESS;
  CompOp comp = condition.comp;
  if (comp < EQUAL_TO || comp >= NO_OP) {
    LOG_WARN("invalid compare operator : %d", comp);
    return RC::INVALID_ARGUMENT;
  }

  filter_unit = new FilterUnit;
  switch (condition.left_type) {
    case ConditionType::C_ATTR: {
      Table           *table = nullptr;
      const FieldMeta *field = nullptr;
      rc                     = get_table_and_field(db, default_table, tables, condition.left_attr, table, field,p_tables);
      if (rc != RC::SUCCESS) {
        LOG_WARN("cannot find attr");
        return rc;
      }
      FilterObj filter_obj;
      filter_obj.init_attr(Field(table, field));
      filter_unit->set_left(filter_obj);
    } break;
    case ConditionType::C_SQL: {
      Stmt *sub_stmt = nullptr;
      if (condition.left_sql == nullptr) {
        LOG_WARN("cannot create sub select stmt");
        return rc;
      }
      std::vector<std::string> current_tables;
      if(tables!=nullptr){
      for(auto it=tables->begin();it!=tables->end();it++){
        current_tables.push_back(it->first);
      }
      }
      current_tables.insert(current_tables.end(),p_tables.begin(),p_tables.end());
      rc = SelectStmt::create(db, *condition.left_sql, sub_stmt,current_tables);
      if (rc != RC::SUCCESS) {
        LOG_WARN("cannot create sub select stmt");
        return rc;
      }
      FilterObj filter_obj;
      filter_obj.init_sql(sub_stmt);
      filter_unit->set_left(filter_obj);

    } break;
    case ConditionType::C_VALUE: {
      FilterObj filter_obj;
      filter_obj.init_value(condition.left_value);
      filter_unit->set_left(filter_obj);
    } break;
    case ConditionType::C_VALUE_LIST: {
      FilterObj filter_obj;
      filter_obj.init_value_list(condition.left_value_list);
      filter_unit->set_left(filter_obj);
    } break;
    case ConditionType::C_NULL:{
      FilterObj filter_obj;
      filter_obj.init_null();
      filter_unit->set_left(filter_obj);
    }
  }
  // if (condition.left_is_attr) {
  //   Table *table = nullptr;
  //   const FieldMeta *field = nullptr;
  //   rc = get_table_and_field(db, default_table, tables, condition.left_attr, table, field);
  //   if (rc != RC::SUCCESS) {
  //     LOG_WARN("cannot find attr");
  //     return rc;
  //   }
  //   FilterObj filter_obj;
  //   filter_obj.init_attr(Field(table, field));
  //   filter_unit->set_left(filter_obj);
  // }
  // else if (condition.left_is_sql){
  //   Stmt* stmt=nullptr;
  //   if(condition.left_sql==nullptr){
  //     LOG_WARN("cannot create sub select stmt");
  //     return rc;
  //   }
  //   rc=SelectStmt::create(db,*condition.left_sql,stmt);
  //   if(rc!=RC::SUCCESS){
  //     LOG_WARN("cannot create sub select stmt");
  //     return rc;
  //   }
  //   FilterObj filter_obj;
  //   filter_obj.init_sql(stmt);
  //   filter_unit->set_left(filter_obj);
  // }
  // else {
  //   FilterObj filter_obj;
  //   filter_obj.init_value(condition.left_value);
  //   filter_unit->set_left(filter_obj);
  // }
  switch (condition.right_type) {
    case ConditionType::C_ATTR: {
      Table           *table = nullptr;
      const FieldMeta *field = nullptr;
      rc                     = get_table_and_field(db, default_table, tables, condition.right_attr, table, field,p_tables);
      if (rc != RC::SUCCESS) {
        LOG_WARN("cannot find attr");
        return rc;
      }
      FilterObj filter_obj;
      filter_obj.init_attr(Field(table, field));
      filter_unit->set_right(filter_obj);
    } break;
    case ConditionType::C_SQL: {
      Stmt *sub_stmt = nullptr;
      if (condition.right_sql == nullptr) {
        LOG_WARN("cannot create sub select stmt");
        return rc;
      }
      std::vector<std::string> current_tables;
      if(tables!=nullptr){
      for(auto it=tables->begin();it!=tables->end();it++){
        current_tables.push_back(it->first);
      }
      }
      current_tables.insert(current_tables.end(),p_tables.begin(),p_tables.end());
      rc = SelectStmt::create(db, *condition.right_sql, sub_stmt,current_tables);
      if (rc != RC::SUCCESS) {
        LOG_WARN("cannot create sub select stmt");
        return rc;
      }
      FilterObj filter_obj;
      filter_obj.init_sql(sub_stmt);
      filter_unit->set_right(filter_obj);
    } break;
    case ConditionType::C_VALUE: {
      FilterObj filter_obj;
      filter_obj.init_value(condition.right_value);
      filter_unit->set_right(filter_obj);
    } break;
    case ConditionType::C_VALUE_LIST: {
      FilterObj filter_obj;
      filter_obj.init_value_list(condition.right_value_list);
      filter_unit->set_right(filter_obj);
    } break;
    case ConditionType::C_NULL:{
      FilterObj filter_obj;
      filter_obj.init_null();
      filter_unit->set_right(filter_obj);
    }
  }
  // if (condition.right_is_attr) {
  //   Table *table = nullptr;
  //   const FieldMeta *field = nullptr;
  //   rc = get_table_and_field(db, default_table, tables, condition.right_attr, table, field);
  //   if (rc != RC::SUCCESS) {
  //     LOG_WARN("cannot find attr");
  //     return rc;
  //   }
  //   FilterObj filter_obj;
  //   filter_obj.init_attr(Field(table, field));
  //   filter_unit->set_right(filter_obj);
  // }
  // else if(condition.right_is_sql){
  //   Stmt* stmt=nullptr;
  //   if(condition.right_sql==nullptr){
  //     LOG_WARN("cannot create sub select stmt");
  //     return rc;
  //   }
  //   rc=SelectStmt::create(db,*condition.right_sql,stmt);
  //   if(rc!=RC::SUCCESS){
  //     LOG_WARN("cannot create sub select stmt");
  //     return rc;
  //   }
  //   FilterObj filter_obj;
  //   filter_obj.init_sql(stmt);
  //   filter_unit->set_right(filter_obj);
  // }
  // else {
  //   FilterObj filter_obj;
  //   filter_obj.init_value(condition.right_value);
  //   filter_unit->set_right(filter_obj);
  // }
  filter_unit->set_comp(comp);
  filter_unit->set_comb_type(condition.combination_type);
  // 检查两个类型是否能够比较
  bool check=filter_unit->check();
  if(!check){
    LOG_WARN("unit isnot comparable");
    return RC::INVALID_ARGUMENT;
  }
  return rc;
}
